<?php

class Application_Model_Dao_DeliveryorderDetailMapper
{
	protected $_dbTable;
   
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
   
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_DeliveryorderDetail');
		}
		return $this->_dbTable;
	}
   
	public function save(Application_Model_BusiInfo_DeliveryorderDetail $dod)
	{
		$data = array(
			"id" => $dod->get_id(),
			'deliveryorder_id'   => $dod->get_deliveryorderId(),
			'steel_id' => $dod->get_steelId(),
			'specs' => $dod->get_specs(),
			'amount' => $dod->get_amount(),
			'price' => $dod->get_price(),
			'weight' => $dod->get_weight(),
			'subtotal' => $dod->get_subtotal(),
			'note' => $dod->get_note(),
		);
//		Zend_Registry::get("logger")->log($data['customer_id'] . "____",Zend_log::DEBUG);
		$id = $dod->get_id();
		if ($id == null || $id == "") {
			unset($data['id']);
			$record_id = $this->getDbTable()->insert($data);
//			Zend_Registry::get("logger")->log($result,Zend_log::DEBUG);
//			$data['id'] = $record_id;
//			$data['serial_number'] = $record_id;
//			$this->getDbTable()->update($data, array('id = ?' => $record_id));
		} elseif($dod->get_steelId() != "dummy"){
			$this->getDbTable()->update($data, array('id = ?' => $id));
		} else {
			$this->delete($id);
		}
	}
   
	public function find($id)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		return $this->toModel($row);		
	}
   
	public function fetchAll($orderId = null)
	{
		if ($orderId == null) {
			$resultSet = $this->getDbTable()->fetchAll();
		} else {
			$resultSet = $this->getDbTable()->fetchAll("deliveryorder_id = ".$orderId);
		}
		$entries   = array();
		foreach ($resultSet as $row) {	
			$entry = new Application_Model_BusiInfo_DeliveryorderDetail($row->toArray());
			$entries[] = $entry;
		}
		return $entries;
	}
	
	private function toModel($record){
		$dod = new Application_Model_BusiInfo_DeliveryorderDetail(); 
		$dod->set_id($record->id);
	    $dod->set_deliveryorderId($record->deliveryorder_id);
	    $dod->set_steelId($record->steel_id);
	    $dod->set_specs($record->specs);
	    $dod->set_amount($record->amount);
	    $dod->set_price($record->price);
	    $dod->set_weight($record->weight); 
	    $dod->set_subtotal($record->subtotal);  
	    $dod->set_note($record->note);
	
	    return $dod;
		
	}
	
	public function delete($id) {		
		$this->getDbTable()->delete( "id=" . $id);
	}
	public function deleteByDeliveryorder($doId) {		
		$this->getDbTable()->delete( "deliveryorder_id=" . $doId);
	}
}

